import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, Optional

PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from main import Data_Spider
from xhs_utils.common_util import init


def parse_geo(value: Optional[str]) -> Optional[Dict[str, Any]]:
    if value is None:
        return None
    try:
        return json.loads(value)
    except json.JSONDecodeError:
        raise ValueError("Invalid geo JSON payload")


def run():
    parser = argparse.ArgumentParser(description="Run XHS search spider once and persist results.")
    parser.add_argument(
        "--query",
        default="宁波东方理工大学热点事件",  # 默认设置搜索关键词
        help="Search keyword (default: 宁波东方理工大学热点事件)."
    )
    parser.add_argument("--query-num", type=int, default=10, help="Number of notes to fetch.")
    parser.add_argument(
        "--sort-type-choice",
        "--sort-type",
        dest="sort_type_choice",
        type=int,
        default=0,
        help="Sort type choice.",
    )
    parser.add_argument("--note-type", type=int, default=0, help="Note type filter.")
    parser.add_argument("--note-time", type=int, default=0, help="Note time filter.")
    parser.add_argument("--note-range", type=int, default=0, help="Note range filter.")
    parser.add_argument("--pos-distance", type=int, default=0, help="Position distance filter.")
    parser.add_argument("--geo", type=str, default=None, help="Geo JSON payload.")
    parser.add_argument("--save-choice", default="all", help="Save choice for downstream handling.")
    args = parser.parse_args()

    geo = parse_geo(args.geo)
    cookies_str, base_path = init()
    sqlite_file_path = os.path.abspath(os.path.join(base_path["sqlite"], "notes.db"))
    spider = Data_Spider(sqlite_file_path)
    note_list, success, msg = spider.spider_some_search_note(
        args.query,
        args.query_num,
        cookies_str,
        base_path,
        args.save_choice,
        args.sort_type_choice,
        args.note_type,
        args.note_time,
        args.note_range,
        args.pos_distance,
        geo,
    )
    payload = {
        "success": bool(success),
        "message": str(msg) if msg else "",
        "note_urls": note_list,
    }
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run()
